﻿#include "ui_setMotor.h"
#include "ui_ui_setMotor.h"
#include "tool_xml.h"
#include <QMessageBox>
#include <QString>
#include <QDebug>

uiSetMotor::uiSetMotor(QString sn, LocalDev * ld, int m, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::uiSetMotor)
{
    ui->setupUi(this);

    this->m_sn = sn;
    this->m_motorType = m;
    this->m_ld = ld;

    motorSetValue_t value = ld->m_motorSet[m];

    ui->mode->setCurrentIndex(ld->m_motor.at(m).workMode());
    if (value.enable)
    {
        ui->speed->setText(QString::number(value.speed));
        ui->trip->setText(QString::number(value.trip));
        ui->maxPower->setText(QString::number(value.power));
        ui->type->setCurrentIndex(value.type);
    }

    this->m_xml = new ToolXml;
}

uiSetMotor::~uiSetMotor()
{
    delete ui;
    delete this->m_xml;
    this->deleteLater();
}

void uiSetMotor::on_pushButton_clicked()
{
    bool ok = false;

    int mode = ui->mode->currentIndex();
    int type = ui->type->currentIndex();

    float speed = ui->speed->text().toDouble(&ok);
    if (!ok)
    {
        QMessageBox::warning(this, "速度错误", "输入的速度值有误！");
        return;
    }

    float trip = ui->trip->text().toDouble(&ok);
    if (!ok)
    {
        QMessageBox::warning(this, "行程错误", "输入的行程值有误！");
        return;
    }
    float power = ui->maxPower->text().toDouble(&ok);
    if (!ok)
    {
        QMessageBox::warning(this, "功率错误", "输入的功率上限值有误！");
        return;
    }

    motorSetValue_t * motor = &m_ld->m_motorSet[m_motorType];
    motor->enable = true;
    motor->power = power;
    motor->speed = speed;
    motor->trip = trip;
    motor->type = type;

    Motor m = m_ld->m_motor.at(m_motorType);
    m.setWorkMode(mode);
    m_ld->m_motor.replace(m_motorType, m);

    QString xmlBuf = this->m_xml->makeSetMotor(m_sn, m_ld, m_motorType, mode, type, speed, trip, power);

    emit setMotor(xmlBuf);
}
